package com.medical.data.fiflter;

import com.medical.data.component.LoginUserThreadLocal;
import com.medical.data.config.RedisCache;
import com.medical.data.service.TokenSerivce;
import com.medical.data.utils.JwtUtils;
import com.medical.data.utils.RenderUtil;
import com.medical.data.utils.Result;
import com.medical.data.utils.ResultCode;
import com.medical.data.vo.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@Configuration
@Component
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true, jsr250Enabled = true)  //开启权限验证功能
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {


    @Autowired
    private RedisCache redisCache;

    @Autowired
    private TokenSerivce tokenSerivce;

    public final static List<String> noFilter = Arrays.asList("/api/**",
            "/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**",
            "/user/getPublicKey",
            "/user/updatePassword",
            "/doc.html/**",
            "/favicon.ico",
            "/checker/admin/Add",
            "/static/**",
            "/css/**",
            "/js/**",
            "/img/**",
            "/swagger-ui/**",
            "/swagger-ui/index.html",
            "/swagger-ui/index.html/**",
            "/v3/**",
            "/front/user/loginUser",
            "/front/user/reg",
            "http://localhost:8080/"
    );


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
       log.info("请求地址=====>"+request.getRequestURL());
       if (noFilter.contains(request.getRequestURI())){
           //放行
           filterChain.doFilter(request, response);
           return;
       }
        Map<String,Object> map = new HashMap<>();
        Enumeration<String> paraNames=request.getParameterNames();
        for(Enumeration e=paraNames;e.hasMoreElements();){

            String thisName=e.nextElement().toString();
            String thisValue=request.getParameter(thisName);
            map.put(thisName,thisValue);
        }
        log.info("请求参数========>{}",map);
//       logger.info(is.isResolveDevice(request));
        //获取token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }
        //判断token是否有效
        if (!JwtUtils.checkToken(request)){
            RenderUtil.renderJson(response, Result.error().code(ResultCode.UNLOGINUSER.getCode()).message(ResultCode.UNLOGINUSER.getDesc()));
            return;
        }
        //通过token获取用户信息
        LoginUser loginUser = tokenSerivce.getLoginUser(request);
        if(Objects.isNull(loginUser)){
            RenderUtil.renderJson(response, Result.error().code(ResultCode.UNLOGINUSER.getCode()).message(ResultCode.UNLOGINUSER.getDesc()));
            return;
        }
        //存入SecurityContextHolder
//        //获取权限信息封装到Authentication中，在这里没有权限会被拦截
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser,null,null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
//        //将用户放入到本地线程中
        LoginUserThreadLocal.set(loginUser);
        //放行
        filterChain.doFilter(request, response);
    }

}
